package com.itheima.tanhua.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.autoconfig.template.HuanXinTemplate;
import com.itheima.tanhua.api.db.UserApi;
import com.itheima.tanhua.api.db.UserInfoApi;
import com.itheima.tanhua.api.mongodb.FriendApi;
import com.itheima.tanhua.api.mongodb.MessageApi;
import com.itheima.tanhua.api.mongodb.UserLikeApi;
import com.itheima.tanhua.enums.Constants;
import com.itheima.tanhua.pojo.db.User;
import com.itheima.tanhua.pojo.db.UserInfo;
import com.itheima.tanhua.pojo.db.Announcement;
import com.itheima.tanhua.vo.CommentsListVo;
import com.itheima.tanhua.vo.PageResult;
import com.itheima.tanhua.vo.UserInfoVo;
import com.itheima.tanhua.vo.db.UserLike;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MessagesService {

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private FriendApi friendApi;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserLikeApi userLikeApi;


    //通过环信的id查询用户信息
    public UserInfoVo findUserinfo(String huaxinId) {
        //通过huanxinId 查询用户的id
        User user = userApi.findByHuanxinId(huaxinId);
        //通过用户id 获取用户的详细信息
        UserInfo userInfo = userInfoApi.selectById(user.getId());
        UserInfoVo vo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, vo); //copy同名同类型的属性
        if (userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }
        return vo;
    }

    //添加联系人
    public void contacts(Long friendId) {
        //1.在环信中添加好友
        //1.1 查询当前friend中是否有uid和friendId的数据
        //获取当前用户的uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));

        //未添加好友
        //2.环信添加好友成功,再在friend中添加两条消息   两个用户需要互相注册好友   添加到friend集合中
        Boolean aBoolean = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + uid, Constants.HX_USER_PREFIX + friendId);
        if (!aBoolean) {
            //添加失败
            throw new RuntimeException("环信添加朋友失败");
        }
        //在mongodb中添加uid和friendId的朋友关系
        friendApi.saveContacts(uid, friendId);
    }

    //好友的分页列表
    public PageResult contactsList(String keyword, Integer page, Integer pagesize) {
        //获取当前用户的uid
        String redisKey = "CHECK_ID";
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get(redisKey));
        //通过uid获取所有的好友id 的id集合   mongodb
        List<Long> friendIds = friendApi.findFriendIds(uid);
        //通过朋友的id查询他的详细信息 mysql中查询
        List<UserInfo> userInfoList = userInfoApi.findContactsList(friendIds, keyword, page, pagesize);

        List<CommentsListVo> vos = new ArrayList<>();
        //组装数据

        for (UserInfo userInfo : userInfoList) {
            CommentsListVo vo = new CommentsListVo();
            if (ObjectUtil.isNotEmpty(userInfo)) {
                BeanUtil.copyProperties(userInfo, vo);
                vo.setUserId("hx" + userInfo.getId().toString());
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, vos, 0, 10);
    }

    @DubboReference
    MessageApi messageApi;

    @GetMapping("announcements")
    public PageResult getAllAnnoun(Integer page,
                                   Integer pagesize) {
        Page<Announcement> ipage = messageApi.getAllMessgae(page, pagesize);
        PageResult pageResult = new PageResult(page, pagesize, ipage.getRecords(), Convert.toInt(ipage.getPages()), Convert.toInt(ipage.getTotal()));
        return pageResult;
    }

    /**
     * 喜欢列表
     *
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult getAllLoves(Integer page, Integer pagesize) {
        Long uid = Convert.toLong(stringRedisTemplate.opsForValue().get("CHECK_ID"));
        //获取喜欢人的id集合
        List<Long> list = userLikeApi.getLove(uid);
        //
        List<UserInfo> userInfoList = userInfoApi.findByIds(list);
        List<UserLike> userLikes = new ArrayList<>();
        //分装对象返回
        for (UserInfo userInfo : userInfoList) {
            UserLike userLike = new UserLike();
            BeanUtil.copyProperties(userInfo, userLike);
            userLikes.add(userLike);
        }
        List<UserLike> collect = userLikes.stream().skip((page - 1) * pagesize).limit(pagesize).collect(Collectors.toList());
        int total=userLikes.size();
        Integer pages=total/pagesize;
        if (total%pagesize!=0){
            pages++;
        }
        PageResult pageResult=new PageResult(page,pagesize,collect,pages,userLikes.size());
        return pageResult;
    }
}
